package com.yourenbang.lingyun.transaction.web.service.impl.pay.transaction;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.constants.enums.table.PayTransactionEnum;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.core.util.date.LocalDateUtils;
import com.yourenbang.lingyun.domain.Terminal21;
import com.yourenbang.lingyun.transaction.constant.LklTransTypeEnum;
import com.yourenbang.lingyun.transaction.web.domain.vo.pay.haike.HkTransactionVO;
import com.yourenbang.lingyun.transaction.web.service.PayTransactionFormatService;
import com.yourenbang.terminal.api.service.RpcYxyTerminalService;
import com.yourenbang.transaction.api.model.vo.pay.PayTransaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

/**
 * 海科交易格式化
 */
@Service
@Slf4j
public class HaikePayTransactionFormatServiceImpl implements PayTransactionFormatService {
    @Autowired
    private RpcYxyTerminalService rpcYxyTerminalService;

    @Override
    public PayTransaction payTransactionFormat(JSONObject jsonObject) {
        log.info("海科格式化交易推送入参:{}", jsonObject.toJSONString());
        HkTransactionVO transactionVO = jsonObject.toJavaObject(HkTransactionVO.class);
        PayTransaction payTransaction = new PayTransaction();
        payTransaction.setMerchantNo(transactionVO.getMercId());
        payTransaction.setMerchantName(transactionVO.getMercNm());
        payTransaction.setOrderNo(transactionVO.getLogNo());
        payTransaction.setTransactionNo(transactionVO.getLogNo());
        payTransaction.setSysRef((transactionVO.getLogNo()));
        payTransaction.setTransactionAmount(transactionVO.getTxnAmt());
        if (Objects.nonNull(transactionVO.getMercFeeAmt())) {
            payTransaction.setTransactionFee(transactionVO.getMercFeeAmt());
        }
        try {
            payTransaction.setRate(new BigDecimal(transactionVO.getFeeRate()).multiply(new BigDecimal("100")).intValue());
        } catch (Exception e) {
            KLog.warn("海科计算费率错误", e);
        }
        payTransaction.setCardFlag(formatCardFlagHk(transactionVO.getCrdFlg(), transactionVO.getTxnCd()));
        payTransaction.setTerminalId(transactionVO.getTrmNo());
        payTransaction.setSn(transactionVO.getSnNo());
        payTransaction.setTransactionCardNo(transactionVO.getCrdNo());
        payTransaction.setTransactionCardType(formatCardFlagHk(transactionVO.getCrdFlg(), transactionVO.getTxnCd()));
        payTransaction.setStatus(formatTradeStatus(transactionVO.getTtxnSts()));
        LocalDateTime transTime = LocalDateTime.now();
        if (StringUtils.isNotBlank(transactionVO.getTxnTm())) {
            transTime = LocalDateUtils.stringToLocalDateTime(transactionVO.getTxnTm(), DateFormat.DATETIME_COMPACT.getPartten());
        }
        payTransaction.setTransactionTime(transTime);
        payTransaction.setTransactionMonth(LocalDateUtils.localDateTimeByFormat(transTime, DateFormat.DATE_MONTH.getPartten()));
        payTransaction.setTransactionDay(LocalDateUtils.localDateTimeByFormat(transTime, DateFormat.DATE_COMPACT.getPartten()));
        payTransaction.setWithdrawalFee(transactionVO.getMercFeeAmt());
        if (Objects.nonNull(transactionVO.getBusinessThrAmt())) {
            //d0手续费
            payTransaction.setFeeAmt(transactionVO.getBusinessThrAmt());
        }
        try {
            payTransaction.setAccAmt(payTransaction.getTransactionAmount().subtract(payTransaction.getFeeAmt()).subtract(payTransaction.getTransactionFee()));
        } catch (Exception e) {
            log.warn("计算海科到账金额失败:{}", payTransaction.toJSON());
        }
        payTransaction.setWithdrawalStatus(PayTransactionEnum.WithdrawalStatusEnum.STATUS_40.getCode());

        Terminal21 terminal21 = rpcYxyTerminalService.getTerminalBySn(transactionVO.getSnNo());
        if (Objects.isNull(terminal21)) {
            return null;
        }
        payTransaction.setChannelId(terminal21.getChannelId());
        payTransaction.setPlatNo(PlatNoEnums.YXY.getCode());
        payTransaction.setIsDel(false);
        if (StringUtils.equalsAny(transactionVO.getTxnBusTyp(), "04", "03")) {
            payTransaction.setTransType(LklTransTypeEnum.TYPE_412001.getTransType());
        } else if (Objects.nonNull(transactionVO.getIccPayAmt()) && transactionVO.getIccPayAmt().compareTo(BigDecimal.ZERO) > 0) {
            payTransaction.setTransType(LklTransTypeEnum.TYPE_012003.getTransType());
            payTransaction.setIccPayAmt(transactionVO.getIccPayAmt());
        }
        //分润标识
        payTransaction.setProfitFlag(checkIsProfitFlagHk(payTransaction));

        return payTransaction;
    }

    /**
     * 电银判断交易状态
     *
     * @param respCode
     * @return
     */
    private Short formatTradeStatus(String respCode) {
        if (StringUtils.equals(respCode, "S")) {
            return PayTransactionEnum.TransactionStatus.STATUS_10.getCode();
        }
        return PayTransactionEnum.TransactionStatus.STATUS_20.getCode();
    }

    /**
     * 海科判断交易卡类型
     *
     * @param crdFlg 卡类型
     * @param txnCd  交易类型
     * @return
     */
    private String formatCardFlagHk(String crdFlg, String txnCd) {
        /**
         * 交易类型	txnCd	必填
         *      * 01-有卡消费
         *      * 02-有卡撤销
         *      * 03-消费冲正
         *      * 04-预授权
         *      * 05-预授权撤销
         *      * 06-微信消费
         *      * 07-微信消费撤销
         *      * 08-支付宝消费
         *      * 09-支付宝消费撤销
         *      * 10-银联二维码消费
         *      * 11-银联二维码撤销
         *      * 12-云闪付消费
         *      crdflg
         *      05-借记卡 06-贷记卡
         */
        if (StringUtils.equalsAny(txnCd, "08")) {
            return PayTransactionEnum.CardFlagEnum.ALIPAY.getCode();
        }
        if (StringUtils.equalsAny(txnCd, "06")) {
            return PayTransactionEnum.CardFlagEnum.WECHAT.getCode();
        }

        if (StringUtils.equals(txnCd, "10")) {
            return PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode();
        }
        if (StringUtils.equals(crdFlg, "06")) {
            return PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode();
        }
        if (StringUtils.equals(crdFlg, "05")) {
            return PayTransactionEnum.CardFlagEnum.BORROW_CARD.getCode();
        }
        return txnCd + crdFlg;
    }


    //判断是否计入分润
    private boolean checkIsProfitFlagHk(PayTransaction payTransaction) {
        //贷记卡且非押金交易才计入分润
        if (StringUtils.equalsAny(payTransaction.getCardFlag(), PayTransactionEnum.CardFlagEnum.ALIPAY.getCode(),
                PayTransactionEnum.CardFlagEnum.WECHAT.getCode(),
                PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode(), PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode()) &&
                !StringUtils.equals(LklTransTypeEnum.TYPE_412001.getTransType(), payTransaction.getTransType())) {
            return true;
        }
        return false;
    }

    @Override
    public JSONObject dyUrlRequest(String uri, Map<String, Object> bodyJson) {
        return null;
    }

    @Override
    public JSONObject dyUrlRequestByPayType(String uri, Map<String, Object> bodyJson, PayTypeEnum payTypeEnum) {
        return null;
    }
}
